package com.aaa.tars.util;

import com.aaa.tars.dao.UserDao;
import com.aaa.tars.entity.LoginLog;
import com.aaa.tars.entity.User;
import com.aaa.tars.service.LoginLogService;
import com.aaa.tars.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @FileName: RecordLoginLogUtil
 * @Description: 登录日志记录工具类
 * @Author: xm
 * @CreateTime: 2025/9/22 19:58
 * @Version: 1.0.0
 */
@Component
@Aspect
public class RecordLoginLogUtil {

    @Resource
    private LoginLogService loginLogService;

    @Resource
    private UserDao userDao;

    @Resource
    private HttpSession session;

    @Resource
    private HttpServletRequest request;

    /**
     * 定义切入点：拦截 UserServiceImpl 中的 checkUser 方法
     */
    @Pointcut("execution(* com.aaa.tars.service.impl.UserServiceImpl.checkUser(..))")
    public void loginPointCut() {
    }

    /**
     * 后置通知：登录成功后记录日志
     *
     * @param joinPoint 连接点
     */
    @AfterReturning(pointcut = "loginPointCut()")
    public void recordLoginSuccess(JoinPoint joinPoint) {
        recordLoginLog(joinPoint,0,null);
    }

    /**
     * 异常通知：登录失败时记录日志
     *
     * @param joinPoint 连接点
     * @param e         异常
     */
    @AfterThrowing(pointcut = "loginPointCut()", throwing = "e")
    public void recordLoginFail(JoinPoint joinPoint, Exception e) {
        recordLoginLog(joinPoint,1,e);
    }

    /**
     * 封装记录登录日志的方法
     *
     * @param joinPoint 连接点
     * @param status    登录状态：0-成功，1-失败
     */
    private void recordLoginLog(JoinPoint joinPoint, Integer status,Exception e) {
        LoginLog loginLog = new LoginLog();

        // 获取当前登录用户信息（如果已登录）
        User user = (User) session.getAttribute("userInfo");
        if (user != null) {
            loginLog.setUserName(user.getUserName());
        } else {
            loginLog.setUserName("未登录");
        }

        // 设置登录IP
        String remoteAddr = request.getRemoteAddr();
        loginLog.setLoginIp(remoteAddr);

        // 设置登录地点（可选，这里简化为固定值）
        loginLog.setLoginLocation("郑州");

        // 设置登录类型（0-PC端，1-移动端，2-其他）
        // 可根据请求头判断，此处默认为 PC 端
        loginLog.setLoginType(0);

        // 设置登录状态
        loginLog.setLoginStatus(status);

        //异常信息
        if(e!=null){
            loginLog.setErrorMsg(e.getClass().getName());
        }

        // 设置登录时间
        loginLog.setLoginTime(new Date());

        // 保存日志
        loginLogService.add(loginLog);
    }
}
